import re
import zipfile

from src.formats.ReadZipFiles import ReadZipFile
import os
import gzip


def getSrcPath():
    return os.path.dirname(os.path.dirname(os.path.realpath(__file__)))


class ZipManager:
    def __init__(self, filePath):
        self.srcPath = getSrcPath()
        # 打包文件路径
        self.filePath = filePath
        # 打包文件zipFile对象,提供读取打包文件内文件的方法
        self.tilesFile = ReadZipFile(filePath)

    # 根据路径获取文件
    #   根据路径获取包内文件，如果报错那么
    #       1.判断其是否是文件夹，然后遍历拼合info文件中的默认文件名，首先对其进行存在性判断，若存在则返回
    #       2.如果是文件，遍历拼合info文件中的默认扩展名，首先对其进行存在性判断，若存在则返回
    def getFile(self, full_path, fileName, file_ext):
        suffix, mimetype, ziptype = self.get_suffix(full_path, fileName, file_ext)
        json = self.tilesFile.readSubFile(full_path + suffix)
        self.tilesFile.closeSubFile(full_path + suffix)
        return json, ziptype, mimetype

    def get_suffix(self, full_path, file_name, file_suffix):
        tag = self.tilesFile.pathIsExists(full_path + '/')
        suffix = ''
        ziptype = ''
        mimetype = 'text/html'
        if tag == 1:
            for filename in file_name:
                if self.tilesFile.pathIsExists(full_path + '/' + filename) == 1:
                    suffix = '/' + filename
        else:
            for suffix_name in file_suffix:
                if self.tilesFile.pathIsExists(full_path + suffix_name) == 1:
                    suffix = suffix_name
        if suffix.find('.json') > 0:
            mimetype = 'application/json'
        if suffix.find('.gz') > 0:
            ziptype = 'gzip'
        return suffix, mimetype, ziptype
